package com.yan.club.auth.handler;

import com.alibaba.fastjson.JSON;
import com.yan.club.auth.utils.WebUtils;
import com.yan.club.result.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.yan.club.result.ResultCode.INTERNAL_SERVER_ERROR;
import static com.yan.club.result.ResultCode.UNAUTHORIZED;

/**
 * @author 彦
 * @since 2024/1/22 09:01
 * 自定义认证失败的处理器
 */
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        //输出异常信息
        authException.printStackTrace();

        //判断是登录才出现异常(返回'用户名或密码错误')，还是没有登录就访问特定接口才出现的异常(返回'需要登录后访问')，
        // 还是其它情况(返回'出现错误')
        Result<String> result;
        if (authException instanceof BadCredentialsException) {
            result = Result.error(INTERNAL_SERVER_ERROR.code, "用户名或密码错误");
        } else if (authException instanceof InsufficientAuthenticationException) {
            result = Result.error(UNAUTHORIZED.code, "需要登录后访问");
        } else {
            result = Result.error(INTERNAL_SERVER_ERROR.code, "认证或授权失败");
        }

//         返回给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}